﻿using IOP.SgrA;
using IOP.SgrA.ECS;
using IOP.SgrA.Input;
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace VkSample413
{
    public class TransformSystem : ComponentSystem
    {

        private float AngleX = 90.0f;
        private float AngleY;
        private int depthOffsetFlag = 0;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contextManager"></param>
        public TransformSystem()
        {
        }

        public override void Initialization()
        {
            float x = -250.0f;
            Vector3 scale = Vector3.One;
            ContextManager.Foreach<Group>((group) =>
            {
                group.Transform = new TransformComponent
                {
                    Position = new Vector3(x, 0, 0),
                };
                x += 500.0f;
                return group;
            });
        }

        public override void Update(TimeSpan timeSpan)
        {
            float diffX = 0;
            float diffY = 0;
            if(Input.GetMouseButtonState(MouseButton.ButtonLeft).Action == InputAction.Click)
            {
                depthOffsetFlag++;
                depthOffsetFlag %= 3;
            }
            if (Input.GetMouseButtonState(MouseButton.ButtonLeft).Action == InputAction.Press)
            {
                Vector2 p = Input.GetMousePositionDelta();
                diffX = p.X;
                diffY = p.Y;
            }
            AngleX += diffX * 180 / 200;
            AngleY += diffY * 180 / 200;
            ContextManager.Foreach<Group>((group) =>
            {
                Context context = ContextManager.GetContext(group.Entity);
                ref MVPMatrix mvp = ref context.GetMVPMatrix();
                mvp.ModelMatrix = Matrix4x4.CreateTranslation(group.Transform.Position) *
                Matrix4x4.CreateRotationY(AngleX / 180.0f * MathF.PI) *
                Matrix4x4.CreateRotationX(AngleY / 180.0f * MathF.PI);
                var render = context.GetContextRenderGroup();
                render.SetCustomPropery("depthOffsetFlag", depthOffsetFlag);
                context.PushToRenderGroup();
            });
        }

        public struct Group
        {
            public Entity Entity;
            public TransformComponent Transform;
        }
    }
}
